import tool.ListNode;
import tool.createList;
import tool.listPrint;

import javax.sound.midi.Soundbank;

/**
 * @Description: 两两交换链表中的节点
 * 给你一个链表，两两交换其中相邻的节点，并返回交换后链表的头节点。
 * 你必须在不修改节点内部的值的情况下完成本题（即，只能进行节点交换）。
 * @Date:Create in 9:59  2022/6/28
 */
public class swapPairs0024 {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 4, 5};
        ListNode head = createList.create_List(arr);
        listPrint.printListHead(head);
        ListNode res = swapPairs2(head);
        System.out.println("**********");
        listPrint.printListHead(res);
    }

    //暴力解法
    public static ListNode swapPairs1(ListNode head) {
        if (head == null) return null;
        ListNode cur = head.next;
        ListNode pre = head;
        if (cur == null) return head;

        swapItem(pre, cur);
        head = cur;
        ListNode temp = pre;
        if (pre.next == null) {
            return head;
        } else {
            pre = pre.next;
            cur = pre.next;
            while (cur != null) {
                swapItem(pre, cur);
                temp.next = cur;
                temp = pre;
//                System.out.println("****");
//                System.out.println(pre.val);
//                System.out.println(cur.val);
//                System.out.println("****");
                if (pre.next != null) {
                    pre = pre.next;
                    cur = pre.next;
                } else {
                    break;
                }
            }
        }
        return head;
    }

    private static void swapItem(ListNode pre, ListNode cur) {
        pre.next = cur.next;
        cur.next = pre;
    }

    //递归解法
    public static ListNode swapPairs2(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode next = head.next;
        ListNode newnode = swapPairs2(next.next);

        next.next = head;
        head.next = newnode;

        return next;
    }


}
